//
//  JoinProjectViewController.m
//  WideHelp
//
//  Created by ENERGY on 2018/8/7.
//  Copyright © 2018年 ENERGY. All rights reserved.
//首页-升级-立即升级-符合条件，继续

#import "JoinProjectViewController.h"
#import "JoinProjectTableViewCell.h"
#import "DeleteView.h"
#import "RelationView.h"
#import "RechargeView.h"
@interface JoinProjectViewController ()<UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong)UITableView * tableView;
@property (nonatomic, strong)UIView * footerView;
@property (nonatomic, strong)NSMutableArray * blockCellData;
@property (nonatomic, strong)NSMutableArray * cellArrData;
//@property (nonatomic, strong)NSMutableArray * fakeData;
@property (nonatomic, assign)int sectionDeleteNum;//删除数据的具体组号
@property (nonatomic, strong)RelationView * relationView;
@property (nonatomic, strong)RechargeView * rechargeView;
@property (nonatomic, assign)int currentPage;
@property (nonatomic, strong)NSIndexPath * index;//判断所填写内容为空

@property (nonatomic, strong)NSString * getDataRelationStr;
@property (nonatomic, strong)NSString * getDataRela_idStr;
@property (nonatomic, strong)NSString * getDataNameStr;
@property (nonatomic, strong)NSString * getDataCard_idStr;
@property (nonatomic, strong)NSString * getDataRecharge_amountStr;

@property (nonatomic, assign)int rechargeSection;
@property (nonatomic, assign)int rechargeRow;

@property (nonatomic, assign)int relationSection;
@property (nonatomic, assign)int relationRow;
@end

@implementation JoinProjectViewController(networking)
- (void)getFamily{
    NSDictionary *parameters = @{
                                 @"userId":[UserModel sharedInstanced].userID,
                                 @"cookie":[UserModel sharedInstanced].cookie,
                                 @"page":@(self.currentPage),
                                 @"size":@(5)
                                 };
    [self showprogressHUD];
    [[AFAppDotNetAPIClient sharedClient] POST:@"plan/getFamily" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self hiddenProgressHUD];
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        if ([responseObject[@"msg"] isEqualToString:@"success"]) {
            NSMutableArray * arr = [NSMutableArray array];
            NSMutableDictionary * arrDic = [NSMutableDictionary dictionary];//每个数组元素的字典
            NSMutableDictionary * noneNilArrDic = [NSMutableDictionary dictionary];
            [arr addObjectsFromArray:responseObject[@"list"]];
            if (self.currentPage == 1) {
                [self.cellArrData removeAllObjects];
            }
            
            for (int i = 0; i<arr.count; i++) {
                arrDic = arr[i];
                NSMutableArray * insertCellDataArr = [NSMutableArray array];
                for (NSString * key in arrDic) {
                    if ([arrDic objectForKey:key] == nil) {
                        [noneNilArrDic setObject:@"" forKey:[arrDic objectForKey:key]];
                    }else{
                        [noneNilArrDic setObject:[arrDic objectForKey:key] forKey:key];
                    }
                    if ([key isEqualToString:@"card_id"]) {
                        [insertCellDataArr addObject:@{@"title":@"身份证:", @"placeHolder":noneNilArrDic[@"card_id"]}];
                    }
                    if ([key isEqualToString:@"relation"]) {
                        [insertCellDataArr addObject:@{@"title":@"关系:", @"placeHolder":noneNilArrDic[@"relation"]}];
                    }
                    if ([key isEqualToString:@"name"]) {
                        [insertCellDataArr addObject:@{@"title":@"姓名:", @"placeHolder":noneNilArrDic[@"name"]}];
                    }
                    if ([key isEqualToString:@"recharge_amount"]) {
                        [insertCellDataArr addObject:@{@"title":@"充值金额:", @"placeHolder":noneNilArrDic[@"recharge_amount"]}];
                    }
                }
                [self.cellArrData addObject:insertCellDataArr];
            }
            if (arr.count<5) {
                [self.cellArrData addObject:self.blockCellData];
            }
            [self.tableView reloadData];
        }else{
            ShowMessage(responseObject[@"msg"]);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self hiddenProgressHUD];
        [self showError:error];
    }];
}
- (void)addFamily{
    NSDictionary *parameters = @{
                                 @"userId":[UserModel sharedInstanced].userID,
                                 @"cookie":[UserModel sharedInstanced].cookie,
                                 @"name":@"name",
                                 @"rela":@"rela",
                                 @"amount":@"30"
                                 };
    [self showprogressHUD];
    [[AFAppDotNetAPIClient sharedClient] POST:@"plan/addFamily" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self hiddenProgressHUD];
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        if ([responseObject[@"msg"] isEqualToString:@"success"]) {
//            if (self.currentPage == 1) {
//                self.cellArrData = @[self.blockCellData].mutableCopy;
//            }
//            [self.cellArrData addObjectsFromArray:responseObject[@"list"]];
            [self.tableView reloadData];
        }else{
            ShowMessage(@"msg");
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self hiddenProgressHUD];
        [self showError:error];
    }];
}
@end
@implementation JoinProjectViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"加入计划";
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    [self.view addSubview:self.tableView];
    //控件搭建
    [self setUpViews];
    //关系
    self.relationView = [[RelationView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    //充值
    self.rechargeView = [[RechargeView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    
    __weak typeof (self)weakSelf = self;
    self.rechargeView.rechargeStringBlock = ^(NSString * rechargeString) {
        NSIndexPath * index = [NSIndexPath indexPathForRow:weakSelf.rechargeRow inSection:weakSelf.rechargeSection];
        JoinProjectTableViewCell * cell = (JoinProjectTableViewCell *)[weakSelf.tableView cellForRowAtIndexPath:index];
        cell.nameTextField.text = rechargeString;
    };
    self.relationView.relationStringBlock = ^(NSString * relationString) {
        NSIndexPath * index = [NSIndexPath indexPathForRow:weakSelf.relationRow inSection:weakSelf.relationSection];
        JoinProjectTableViewCell * cell = (JoinProjectTableViewCell *)[weakSelf.tableView cellForRowAtIndexPath:index];
        cell.nameTextField.text = relationString;
    };
    self.currentPage = 1;
    [self getFamily];//获取列表
}

#pragma mark - init
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - NAVI_HEIGHT - BOTTOM_HEIGHT - 104/WIDTH_6_SCALE) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerClass:[JoinProjectTableViewCell class] forCellReuseIdentifier:NSStringFromClass([JoinProjectTableViewCell class])];
        _tableView.tableFooterView = self.footerView;
        _tableView.rowHeight = 42/WIDTH_6_SCALE;
        _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
            self.currentPage ++;
            for (int i = 0; i<self.blockCellData.count; i++) {
                self.index = [NSIndexPath indexPathForItem:i inSection:self.cellArrData.count - 1];
                JoinProjectTableViewCell * cell = (JoinProjectTableViewCell *)[self.tableView cellForRowAtIndexPath:self.index];
                if (!cell.nameTextField.text || [cell.nameTextField.text length] == 0 || [cell.nameTextField.text isEqualToString:@""]) {
                    if (i == 2) {
                        NSLog(@"可空");
                    }else{
                        ShowMessage(@"请填写完整信息");
                        [self.tableView.mj_footer endRefreshing];
                        return;
                    }
                }
            }
            [self getFamily];
        }];
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            self.currentPage = 1;
            [self getFamily];
        }];
//        _tableView.backgroundColor = [UIColor orangeColor];
    }return _tableView;
}

- (UIView *)footerView{
    if (!_footerView) {
        _footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 42/WIDTH_6_SCALE)];
        UIButton * addFamilyBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, _footerView.height)];
        [addFamilyBtn setTitle:@"  为更多加人添加" forState:UIControlStateNormal];
        [addFamilyBtn addTarget:self action:@selector(addFamilyBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        addFamilyBtn.titleLabel.font = DEF_FontSize_16;
        [addFamilyBtn setTitleColor:getColor(greenBGColor) forState:UIControlStateNormal];
        [addFamilyBtn setBackgroundColor:[UIColor whiteColor]];
        [addFamilyBtn setImage:[UIImage imageNamed:@"add_icon"] forState:UIControlStateNormal];
        [_footerView addSubview:addFamilyBtn];
    }return _footerView;
}

- (void)setUpViews{
    //底层灰色背景
    __weak typeof (self)weakSelf = self;
    UIView * grayBGView = [[UIView alloc] init];
    grayBGView.backgroundColor = getColor(@"eeeeee");
    [self.view addSubview:grayBGView];
    //白色背景
    UIView * whiteBGView = [[UIView alloc] init];
    whiteBGView.backgroundColor = [UIColor whiteColor];
    [grayBGView addSubview:whiteBGView];
    //确认加入互助按钮
    UIButton * sureJoinBtn = [[UIButton alloc] init];
    [sureJoinBtn setTitle:@"确认加入互助" forState:UIControlStateNormal];
    [sureJoinBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [sureJoinBtn setBackgroundColor:getColor(greenBGColor)];
    sureJoinBtn.layer.cornerRadius = 4;
    sureJoinBtn.layer.masksToBounds = YES;
    [sureJoinBtn setBackgroundImage:[UIImage imageNamed:@"maself_bg"] forState:UIControlStateNormal];
    [whiteBGView addSubview:sureJoinBtn];
    //对号
    int checkBtnW = 22/WIDTH_6_SCALE;
    UIButton * checkBtn = [[UIButton alloc] init];
    [checkBtn addTarget:self action:@selector(checkBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [checkBtn setImage:[UIImage imageNamed:@"Unselected_x_icon"] forState:UIControlStateNormal];
    [checkBtn setImage:[UIImage imageNamed:@"Selected_x_icon"] forState:UIControlStateSelected];
    [whiteBGView addSubview:checkBtn];
    //说明文本
    UILabel * instructionTitleLab = [[UILabel alloc] init];
    instructionTitleLab.text = @"我已阅读并同意";
    instructionTitleLab.font = DEF_FontSize_10;
    instructionTitleLab.centerY = checkBtn.centerY;
    instructionTitleLab.textColor = getColor(@"c6c6c6");
    [whiteBGView addSubview:instructionTitleLab];
    //计划条款
    UIButton * projectClauseBtn = [[UIButton alloc] init];
    [projectClauseBtn setTitle:@"《计划条款》" forState:UIControlStateNormal];
    [projectClauseBtn setTitleColor:getColor(greenBGColor) forState:UIControlStateNormal];
    projectClauseBtn.titleLabel.font = DEF_FontSize_10;
    [whiteBGView addSubview:projectClauseBtn];
    //会员公约
    UIButton * memberConventionBtn = [[UIButton alloc] init];
    [memberConventionBtn setTitle:@"《会员公约》" forState:UIControlStateNormal];
    [memberConventionBtn setTitleColor:getColor(greenBGColor) forState:UIControlStateNormal];
    memberConventionBtn.titleLabel.font = DEF_FontSize_10;
    [whiteBGView addSubview:memberConventionBtn];
    //及
    UILabel * andLab = [[UILabel alloc] init];
    andLab.text = @"及";
    andLab.textColor = getColor(@"c6c6c6");
    andLab.font = DEF_FontSize_12;
    [whiteBGView addSubview:andLab];
    //健康要求
    UIButton * healthyRequestBtn = [[UIButton alloc] init];
    [healthyRequestBtn setTitle:@"《健康要求》" forState:UIControlStateNormal];
    [healthyRequestBtn setTitleColor:getColor(greenBGColor) forState:UIControlStateNormal];
    healthyRequestBtn.titleLabel.font = DEF_FontSize_10;
    [whiteBGView addSubview:healthyRequestBtn];
    //masonry
    [grayBGView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(weakSelf.view);
        make.bottom.equalTo(weakSelf.view.mas_bottom).mas_offset(-BOTTOM_HEIGHT);
        make.height.mas_offset(104/WIDTH_6_SCALE);
    }];
    [whiteBGView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(grayBGView.mas_left).mas_offset(1/WIDTH_6_SCALE);
        make.width.mas_offset(SCREEN_WIDTH - 2/WIDTH_6_SCALE);
        make.top.equalTo(grayBGView.mas_top).mas_offset(1/WIDTH_6_SCALE);
        make.bottom.equalTo(grayBGView.mas_bottom);
    }];
    [sureJoinBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(whiteBGView.mas_left).mas_offset(15/WIDTH_6_SCALE);
        make.top.equalTo(whiteBGView.mas_top).mas_offset(15/WIDTH_6_SCALE);
        make.width.mas_offset(SCREEN_WIDTH - 30/WIDTH_6_SCALE);
        make.height.mas_offset(40/WIDTH_6_SCALE/WIDTH_6_SCALE);
    }];
    [checkBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(sureJoinBtn.mas_left);
        make.top.equalTo(sureJoinBtn.mas_bottom).mas_offset(13/WIDTH_6_SCALE);
        make.width.height.mas_equalTo(checkBtnW);
    }];
    [instructionTitleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(checkBtn.mas_right).mas_offset(10/WIDTH_6_SCALE);
        make.centerY.equalTo(checkBtn.mas_centerY).mas_offset(-1/WIDTH_6_SCALE);
        make.height.mas_offset(checkBtnW);
    }];
    [projectClauseBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(instructionTitleLab.mas_right);
        make.top.bottom.equalTo(instructionTitleLab);
    }];
    [memberConventionBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(projectClauseBtn.mas_right);
        make.top.bottom.equalTo(instructionTitleLab);
    }];
    [andLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(memberConventionBtn.mas_right);
        make.top.bottom.equalTo(instructionTitleLab);
    }];
    [healthyRequestBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(andLab.mas_right);
        make.top.bottom.equalTo(instructionTitleLab);
    }];
}

- (NSMutableArray *)blockCellData{
    if (!_blockCellData) {
        _blockCellData = @[@{@"title":@"姓名:", @"placeHolder":@"为谁加入，请输入TA的姓名"},
                      @{@"title":@"关系:", @"placeHolder":@"TA是我的"},
                      @{@"title":@"身份证:", @"placeHolder":@"忘记可不填，后续再补"},
                      @{@"title":@"充值金额:", @"placeHolder":@"选择充值金额"}].mutableCopy;
    }return _blockCellData;
}

- (NSMutableArray *)cellArrData{
    if (!_cellArrData) {
        _cellArrData = @[].mutableCopy;
    }return _cellArrData;
}

- (CGRect)getLabelWidthWithLabel:(UILabel *)textLabel withFont:(UIFont *)fontSize{
    CGRect frame = [textLabel.text boundingRectWithSize:CGSizeMake(MAXFLOAT, 22/WIDTH_6_SCALE) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:fontSize} context:nil];
    return frame;
}

#pragma mark - tableViewDelegate和tableViewDataSource
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    JoinProjectTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([JoinProjectTableViewCell class]) forIndexPath:indexPath];
//    if (indexPath.section == self.cellArrData.count) {
//        cell.model = self.blockCellData[indexPath.row];
//    }else{
        cell.model = self.cellArrData[indexPath.section][indexPath.row];
//    }
    if (indexPath.row == 1 || indexPath.row == 3) {
        cell.nameTextField.userInteractionEnabled = NO;
        cell.arrowBtn.hidden = NO;
        cell.coverBtn.hidden = NO;
    }else{
        cell.nameTextField.userInteractionEnabled = YES;
        cell.arrowBtn.hidden = YES;
        cell.coverBtn.hidden = YES;
    }
    __weak typeof (self)weakSelf = self;
    if (indexPath.row == 1) {
        cell.getChooseViewBlock = ^{
            [self.relationView show];
            weakSelf.relationSection = (int)indexPath.section;
            weakSelf.relationRow = (int)indexPath.row;
        };
    }
    if (indexPath.row == 3) {
        cell.getChooseViewBlock = ^{
            [self.rechargeView show];
            weakSelf.rechargeSection = (int)indexPath.section;
            weakSelf.rechargeRow = (int)indexPath.row;
        };
    }
    return cell;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.blockCellData.count;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.cellArrData.count;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    self.sectionDeleteNum = (int)section;
    UIView * sectionHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 44/WIDTH_6_SCALE)];
    sectionHeaderView.backgroundColor = getColor(@"f5f5f5");
    //组标题，第几位
    UILabel * numLab = [[UILabel alloc] initWithFrame:CGRectMake(15/WIDTH_6_SCALE, 0, 80/WIDTH_6_SCALE, sectionHeaderView.height)];
    int sectionNum = self.sectionDeleteNum + 1;
    numLab.text = [NSString stringWithFormat:@"第%i位", sectionNum];
    numLab.textColor = getColor(@"a2a2a2");
    numLab.textAlignment = NSTextAlignmentLeft;
    numLab.font = DEF_FontSize_14;
    [sectionHeaderView addSubview:numLab];
    //删除按钮
    UIButton * deleteBtn = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - 58/WIDTH_6_SCALE, 0, 58/WIDTH_6_SCALE, sectionHeaderView.height)];
    deleteBtn.titleLabel.font = DEF_FontSize_14;
    [deleteBtn setTitle:@"删除" forState:UIControlStateNormal];
    [deleteBtn setTitleColor:getColor(@"a2a2a2") forState:UIControlStateNormal];
    [deleteBtn addTarget:self action:@selector(deleteBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [sectionHeaderView addSubview:deleteBtn];
    if (section == self.cellArrData.count) {
        deleteBtn.hidden = YES;
    }else{
        deleteBtn.hidden = NO;
    }
    return sectionHeaderView;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 44/WIDTH_6_SCALE;
}

#pragma mark - action
- (void)deleteBtnClick:(UIButton *)sender{
    NSLog(@"删除");
    DeleteView * deleteView = [[DeleteView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    deleteView.sureDeleteSection = ^{
        [self.cellArrData removeObjectAtIndex:self.sectionDeleteNum - 1];
        [self.tableView reloadData];
    };
    [deleteView show];
}
- (void)checkBtnClick:(UIButton *)sender{
    sender.selected = !sender.selected;
}
- (void)addFamilyBtnClick:(UIButton *)sender{
    NSLog(@"为更多人添加");
    for (int i = 0; i<self.blockCellData.count; i++) {
        self.index = [NSIndexPath indexPathForItem:i inSection:self.cellArrData.count - 1];
        JoinProjectTableViewCell * cell = (JoinProjectTableViewCell *)[_tableView cellForRowAtIndexPath:self.index];
        if (!cell.nameTextField.text || [cell.nameTextField.text length] == 0 || [cell.nameTextField.text isEqualToString:@""]) {
            if (i == 2) {
                NSLog(@"可空");
            }else{
                ShowMessage(@"请填写完整信息");
                return;
            }
        }
    }
    [self addFamily];
    [self.cellArrData addObject:self.blockCellData];
    [self.tableView reloadData];
}
@end
